package com.wskeee.ec.utils
{
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	public class ResourceLoader
	{
		public function ResourceLoader()
		{
			initLoader();
		}
		
		public var appdomain:ApplicationDomain = ApplicationDomain.currentDomain;
		private var allCompleteHandler:Function;
		private var allProgressHandler:Function;
		private var allIOErrorHandler:Function;
		private var total:int;
		public var skindata:Dictionary = new Dictionary();
		public var skin:Dictionary = new Dictionary();
		/**
		 * 加载资源 
		 * @param urls
		 * @param fun
		 * 
		 */		
		public function loads(urls:Array,complete:Function = null,progress:Function = null,ioError:Function = null):void
		{
			total = urls.length;
			allCompleteHandler = complete;
			allProgressHandler = progress;
			allIOErrorHandler = ioError;
			for (var i:int = 0; i < urls.length; i++) 
			{
				load(urls[i],subLoadComplete);
			}
		}
		
		/**
		 * 追加加载任务 
		 * @param url		{url:xx,domain:ApplicationDomain}
		 * @param complete	Fun
		 * @param progress	Fun
		 * @param ioError	Fun
		 * 
		 */
		public function addLoad(url:Object,complete:Function = null,progress:Function = null,ioError:Function = null):void
		{
			total = 1;
			allCompleteHandler = complete;
			allProgressHandler = progress;
			allIOErrorHandler = ioError;
			load(url,subLoadComplete);
		}
		
		/**
		 * 外部添加皮肤文件 
		 * @param url		资源名/路径
		 * @param content	资源
		 */
		public function addResource(url:String,content:Object):void
		{
			skin[url] = null;
			skin[url] = content;
		}
		
		public function destroy():void
		{
			appdomain = null;
			allCompleteHandler = null;
			allProgressHandler = null;
			allIOErrorHandler = null;
			var i:Object;
			for(i in skindata)
			{
				delete skindata[i];
			}
			skindata = null;
			
			for(i in skin)
			{
				delete skin[i];
			}
			skin = null;
		}
		
		private function subLoadComplete(content:Object):void
		{
			var url:String = currentObj.url;
			skindata[url] = content;
			
			var l:Loader = new Loader();
			l.contentLoaderInfo.addEventListener(Event.COMPLETE,_onLoadCompleted);
			
			var domain:ApplicationDomain = currentObj["domain"] ? currentObj["domain"] : appdomain;
			var lc:LoaderContext = new LoaderContext(false,domain);
			l.loadBytes(content as ByteArray,lc);
			
			function _onLoadCompleted(evt:Event):void
			{
				content = l.content;
				if(content is MovieClip) MovieClip(content).gotoAndStop(1);
				
				skin[currentObj.url] = content;
				
				if(queue.length==0)
				{
					if(allCompleteHandler != null)
						allCompleteHandler();
				}else
				{
					checkQueue();
				}
			}
		}
		
		//=================== sceneLoader ============
		protected var loader:URLLoader;
		protected var completeHandler:Function;
		protected var queue:Array = [];
		protected var working:Boolean = false;
		protected var currentObj:Object;
		
		protected function load(obj:Object,completeHandler:Function):void
		{
			queue.push({url:obj["url"],domain:obj["domain"],completeHandler:completeHandler});
			checkQueue();
		}
		
		protected function checkQueue():void
		{
			if(!working && queue.length>0)
			{
				working = true;
				var obj:Object = queue.shift();
				currentObj = obj;
				this.completeHandler = obj.completeHandler;
				var ur:URLRequest = new URLRequest(obj.url);
				loader.load(ur);
				//Logger.log("Load: "+obj.url,this);
			}
		}
		
		protected function initLoader():void
		{
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE,onLoadComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR,onLoadIOError);
			loader.addEventListener(ProgressEvent.PROGRESS,onLoadProgress);
		}
		
		protected function onLoadComplete(evt:Event):void
		{
			//Logger.log("加载完成！",this);
			completeHandler(loader.data);
			working = false;
		}
		
		protected function onLoadIOError(evt:IOErrorEvent):void
		{
			//Logger.log("加载失败！"+evt.text,this,Logger.LEVEL_ERROR);
			if(allIOErrorHandler != null)
				allIOErrorHandler({errorMessage:evt.text});
		}
		
		protected function onLoadProgress(evt:ProgressEvent):void
		{
			if(allProgressHandler != null)
			{
				var params:Object = {};
				params["loaded"] = total-queue.length;
				params["total"] = total;
				params["bytesLoaded"] = evt.bytesLoaded;
				params["bytesTotal"] = evt.bytesTotal;
				
				allProgressHandler(params);
			}
		}
		
		protected function removeLoader():void
		{
			loader.removeEventListener(Event.COMPLETE,onLoadComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR,onLoadIOError);
			loader.removeEventListener(ProgressEvent.PROGRESS,onLoadProgress);
			loader = null;
		}
		//=================== end ====================
	}
}